// packageD/promoter/index.js
const util = require("../../../utils/util.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        finalList: [
            {
                actual_pay: 0.1,
                addTime: "2025-06-15T11:58:23.87408",
                orders: 888,
                amount: 0.02,
                flag: false,
                fromNikeName: "步游",
                fromUserId: 101,
                id: 33,
                lastUpdateTime: "2025-06-15T11:58:23.87408",
                level: 1,
                persons: 3107,
                orderType: "商品佣金",
                refund_status: "待结账",
                remark: null,
                tenantId: 0,
                title: "0.1元10积分",
                toNikeName: "知行融合🍀软件开发",
                orderAmounts: 636,
                avatarUrl: "https://xssp.xjdio.com/images/Xjd/Category/001/202512160106231ab903d4-3740-4369-8e00-a8572db4b059.png",
            },
            {
                actual_pay: 0.1,
                addTime: "2025-06-15T11:58:23.87408",
                orders: 666,
                amount: 0.02,
                flag: false,
                fromNikeName: "步游",
                persons: 121,
                id: 33,
                lastUpdateTime: "2025-06-15T11:58:23.87408",
                level: 1,
                orderId: 3107,
                orderType: "商品佣金",
                refund_status: "待结账",
                remark: null,
                tenantId: 0,
                title: "0.1元10积分",
                toNikeName: "知行融合🍀软件开发",
                orderAmounts: 636,
                avatarUrl: "https://xssp.xjdio.com/images/Xjd/Category/001/202512160106231ab903d4-3740-4369-8e00-a8572db4b059.png",
            },
            {
                actual_pay: 0.1,
                addTime: "2025-06-15T11:58:23.87408",
                orders: 333,
                amount: 0.02,
                flag: false,
                fromNikeName: "步游",
                persons: 101,
                id: 33,
                lastUpdateTime: "2025-06-15T11:58:23.87408",
                level: 1,
                orderId: 3107,
                orderType: "商品佣金",
                refund_status: "待结账",
                remark: null,
                tenantId: 0,
                title: "0.1元10积分",
                toNikeName: "知行融合🍀软件开发",
                orderAmounts: 636,
                avatarUrl: "https://xssp.xjdio.com/images/Xjd/Category/001/202512160106231ab903d4-3740-4369-8e00-a8572db4b059.png",
            }
        ], // 最终组合后的详细列表
        isLoading: false, // 加载状态
        error: null, // 错误信息
        currentTime: '12:00',
        activeTab: 0,
        searchKey: '*****',
        level1Count: 55,
        level2Count: 88,
        page: 1,
        pageSize: 10,
        isLoading: false,
        distributorlist: null,
        fullList: [
            {
                nickname: '胡萝卜',
                level: 1,
                promotionCount: 88,
                orderCount: 880,
                consumption: '80880.00',
                promotionTime: '2024-07-23 11:33:56'
            },
            // 更多模拟数据...
        ],
        filteredList: []
    },
    formatWeekDates(dates) {
        return dates.map(date => {
            return {
                day: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()],
                date: date.toLocaleDateString(),
                fullDate: date
            };
        });
    },
    getCurrentWeekDates() {
        const today = new Date();
        const dayOfWeek = today.getDay(); // 0是周日，6是周六
        const sunday = new Date(today);
        sunday.setDate(today.getDate() - dayOfWeek);

        const weekDates = [];
        for (let i = 0; i < 7; i++) {
            const date = new Date(sunday);
            date.setDate(sunday.getDate() + i);
            weekDates.push(date);
        }

        return weekDates;
    },
    clickweek() {
        const formattedWeek = this.formatWeekDates(this.getCurrentWeekDates());
        console.log(formattedWeek);
    },

    // 获取组合数据的主方法
    fetchCombinedData: function (tab) {
        this.setData({
            isLoading: true,
            error: null
        });

        // 1. 先获取接口A的数据
        this.fetchListFromApiA(tab)
            .then(listFromA => {
                if (tab == 1) {
                    this.setData({
                        level1Count: listFromA.length,
                    })
                } else if (tab == 2) {
                    this.setData({
                        level2Count: listFromA.length,
                    })
                }
                // var templistFromA=listFromA;
                // 2. 获取所有接口B的请求
                const promises = listFromA.map(item => {
                    const param1 = item.level; // 假设property1是第一个参数
                    const param2 = item.toUserId; // 假设property2是第二个参数
                    const param3 = item.addTime; // 假设property2是第二个参数
                    return this.fetchDetailFromApiB(param1, param2, param3)
                        .then(detail => {
                            // 合并接口A和接口B的数据
                            return {
                                detail // 接口B的详细数据
                            };
                        });
                });

                // 3. 等待所有接口B请求完成
                return Promise.all(promises);
            })
            .then(combinedList => {
                // 4. 更新最终数据
                this.setData({
                    finalList: combinedList,
                    isLoading: false
                });
                this.filterList()
            })
            .catch(error => {
                console.error('获取数据失败:', error);
                this.setData({
                    isLoading: false,
                    error: '数据加载失败，请重试'
                });
            });
    },
    // 获取组合数据的主方法
    fetchCombinedData1: function (tab) {
        this.setData({
            isLoading: true,
            error: null
        });

        // 1. 先获取接口A的数据
        this.fetchListFromApiC(tab)
            .then(listFromA => {
                if (tab == 1) {
                    this.setData({
                        level1Count: listFromA.length,
                    })
                } else if (tab == 2) {
                    this.setData({
                        level2Count: listFromA.length,
                    })
                }
                // var templistFromA=listFromA;
                // 2. 获取所有接口B的请求
                const promises = listFromA.map(item => {
                    const param1 = item.level; // 假设property1是第一个参数
                    const param2 = item.toUserId; // 假设property2是第二个参数
                    const param3 = item.addTime; // 假设property2是第二个参数
                    return this.fetchDetailFromApiD(param1, param2, param3)
                        .then(detail => {
                            // 合并接口A和接口B的数据
                            return {
                                detail // 接口B的详细数据
                            };
                        });
                });

                // 3. 等待所有接口B请求完成
                return Promise.all(promises);
            })
            .then(combinedList => {
                // 4. 更新最终数据
                this.setData({
                    finalList: combinedList,
                    isLoading: false
                });
                this.filterList()
            })
            .catch(error => {
                console.error('获取数据失败:', error);
                this.setData({
                    isLoading: false,
                    error: '数据加载失败，请重试'
                });
            });
    },
    // 获取接口A的数据
    fetchListFromApiA: function (param1) {
        const _this = this;
        // var tempparam1=param1;
        return new Promise((resolve, reject) => {
            _this.GetCommissionLpersons(param1).then(
                (res) => {
                    // res.statusCode === 200 &&
                    if (res.stateCode === 200 && res.data) {
                        resolve(res.data); // 假设返回数据中有list字段
                    } else {
                        reject(new Error('接口A返回数据格式不正确'));
                    }
                }
            )

        });
    },
    // 获取接口A的数据
    fetchListFromApiC: function (param1) {
        const _this = this;
        // var tempparam1=param1;
        return new Promise((resolve, reject) => {
            _this.GetCommissionAllpersons(param1).then(
                (res) => {
                    // res.statusCode === 200 &&
                    if (res.stateCode === 200 && res.data) {
                        resolve(res.data); // 假设返回数据中有list字段
                    } else {
                        reject(new Error('接口A返回数据格式不正确'));
                    }
                }
            )

        });
    },

    // 获取接口B的数据
    fetchDetailFromApiB: function (param1, param2, param3) {
        const _this = this;
        return new Promise((resolve, reject) => {
            _this.GetCommissionLTotal(param1, param2, param3).then(
                (res) => {
                    if (res.stateCode === 200 && res.data?.value) {

                        resolve(res.data.value); // 返回接口B的详细数据
                    } else {

                        reject(new Error('接口B返回数据格式不正确'));
                    }
                }
            )
        });
    },
    // 获取接口B的数据
    fetchDetailFromApiD: function (param1, param2) {
        const _this = this;
        return new Promise((resolve, reject) => {
            _this.GetCommissionAllTotal(param1, param2).then(
                (res) => {
                    if (res.stateCode === 200 && res.data?.value) {

                        resolve(res.data.value); // 返回接口B的详细数据
                    } else {

                        reject(new Error('接口B返回数据格式不正确'));
                    }
                }
            )
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // this.fetchCombinedData(1);
       
    },
    // 获取一级或二级推广员
    GetCommissionLpersons(validateLevel) {
        return wx.Http.post("/CommissionAppService/GetCommissionLpersons", { level: validateLevel });
    },
    GetCommissionAllpersons() {
        return wx.Http.post("/CommissionAppService/GetCommissionAllpersons", {});
    },
    //获取更新推广人详细数据
    GetCommissionLTotal(validateLevel, toUserId, addTime) {
        return wx.Http.post("/CommissionAppService/GetCommissionLTotal", { level: validateLevel, toUserId, addTime });
    },
    //获取更新推广人详细数据
    GetCommissionAllTotal(validateLevel, toUserId, addTime) {
        return wx.Http.post("/CommissionAppService/GetCommissionAllTotal", { toUserId, addTime });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        clearInterval(this.timeInterval)
    },

    setCurrentTime() {
        const date = new Date()
        const time = `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
        this.setData({ currentTime: time })
    },

    switchTab(e) {
        const tab = parseInt(e.currentTarget.dataset.tab)
        this.setData({
            activeTab: tab,
            page: 1
        })
        // this.filterList()
        this.fetchCombinedData(tab + 1);
    },

    onSearch(e) {
        this.setData({ searchKey: e.detail })
        this.filterList()
    },

    loadMore() {
        if (this.data.isLoading) return
        this.setData({ isLoading: true })
        // 模拟加载更多
        setTimeout(() => {
            this.setData({
                page: this.data.page + 1,
                isLoading: false
            })
            this.filterList()
        }, 1000)
    },

    filterList() {
        const { activeTab, searchKey, fullList, page, pageSize } = this.data
        let filtered = fullList.filter(item => {
            // 等级筛选
            if (item.level !== activeTab + 1) return false
            // 搜索筛选
            if (searchKey && !item.nickname.includes(searchKey)) return false
            return true
        })
        // 分页处理
        filtered = filtered.slice(0, page * pageSize)
        this.setData({ filteredList: filtered })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})